const socket = io();
const msgBox = document.getElementById("chat-messages");
const input   = document.getElementById("chatInput");
const btnSend = document.getElementById("chatSend");

function appendMsg(data){
  const div = document.createElement("div");
  div.className = "chat-msg";
  div.innerHTML = `<span class="chat-user">${data.username}</span>
                   <span class="chat-time">${data.timestamp}</span>
                   <div>${data.text}</div>`;
  msgBox.appendChild(div);
  msgBox.scrollTop = msgBox.scrollHeight;
}
// 接收消息
socket.on("new_message", appendMsg);
socket.on("user_join", d=>{
  appendMsg({username:"系统",text:`${d.username} 加入群聊`,timestamp:""});
});
socket.on("user_left", d=>{
  appendMsg({username:"系统",text:`${d.username} 离开群聊`,timestamp:""});
});
// 发送消息
function sendMsg(){
  const txt = input.value.trim();
  if(!txt) return;
  socket.emit("send_message",{text:txt});
  input.value="";
}
input.addEventListener("keydown", e=>{ if(e.key==="Enter") sendMsg(); });
btnSend.addEventListener("click", sendMsg);